<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="物料名称" prop="componentsName">
            <el-input v-model="formData.componentsName" placeholder="请输入物料名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料代码" prop="componentsNo">
            <el-input v-model="formData.componentsNo" placeholder="请输入物料代码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              filterable
              clearable
              :disabled="formData.customerDefault"
              v-model="formData.customerId"
              placeholder="请选择客户"
              class="w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属产品" prop="productId">
            <el-select
              filterable
              clearable
              :disabled="!formData.customerId"
              v-model="formData.productId"
              placeholder="请选择产品"
              class="w-1/1"
            >
              <el-option
                v-for="item in getProductOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料规格" prop="dimension">
            <el-input v-model="formData.dimension" placeholder="请输入物料规格" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="componentsUnit">
            <el-select v-model="formData.componentsUnit" class="w-1/1" placeholder="请选择单位">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_PRODUCT_UNIT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">-->
<!--          <el-form-item label="物料状态" prop="componentsStatus">-->
<!--            <el-select v-model="formData.componentsStatus" class="w-1/1" placeholder="请选择物料状态">-->
<!--              <el-option-->
<!--                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_COMPONENT_STATUS)"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="12">-->
<!--          <el-form-item label="使用状态" prop="useingStatus">-->
<!--            <el-radio-group v-model="formData.useingStatus">-->
<!--              <el-radio value="1">请选择字典生成</el-radio>-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="物料属性" prop="componentsAttributes">
            <el-select v-model="formData.componentsAttributes" class="w-1/1" placeholder="请选择物料属性">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_COMPONENT_ATTRIBUTES)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配置属性" prop="allPurpose">
            <el-select v-model="formData.allPurpose" class="w-1/1" placeholder="请选择配置属性">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_ALL_purpose)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">-->
<!--          <el-form-item label="物料等级" prop="componentsLevel">-->
<!--            <el-input v-model="formData.componentsLevel" placeholder="请输入物料等级" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" :rows="3" maxlength="120"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { ComponentsApi, Components } from '@/api/crm/components'
import * as CustomerApi from "@/api/crm/customer";
import * as ProductApi from "@/api/crm/product";

/** CRM 产品配件物料 表单 */
defineOptions({ name: 'ComponentsForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  customerId: undefined,
  productId: undefined,
  componentsName: undefined,
  componentsNo: undefined,
  dimension: undefined,
  componentsUnit: undefined,
  componentsStatus: undefined,
  useingStatus: undefined,
  componentsAttributes: undefined,
  allPurpose: undefined,
  componentsLevel: undefined,
  remark: undefined,
})
const formRules = reactive({
  componentsName: [{ required: true, message: '物料名称不能为空', trigger: 'blur' }],
  componentsNo: [{ required: true, message: '物料代码不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  // brandId: [{ required: true, message: '品牌不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
  // dimension: [{ required: false, message: '物料规格不能为空', trigger: 'blur' }],
  // // ownerUserId: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  // price: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
  // stockNo: [{ required: true, message: '库存不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const customerList = ref([]) // 客户列表的数据
const productList = ref<ProductApi.ProductVO[]>([]) // 产品列表
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  productList.value = await ProductApi.getProductSimpleList()

  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ComponentsApi.getComponents(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Components
    if (formType.value === 'create') {
      await ComponentsApi.createComponents(data)
      message.success(t('common.createSuccess'))
    } else {
      await ComponentsApi.updateComponents(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerId: undefined,
    productId: undefined,
    componentsName: undefined,
    componentsNo: undefined,
    dimension: undefined,
    componentsUnit: undefined,
    componentsStatus: undefined,
    useingStatus: undefined,
    componentsAttributes: undefined,
    allPurpose: undefined,
    componentsLevel: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}

const getProductOptions = computed(() =>
  productList.value.filter((item) => item.customerId == formData.value.customerId)
)
</script>
